package com.example.demo2.action;

import com.example.demo2.bean.Cd;
import com.example.demo2.define.CDEvents;
import com.example.demo2.define.CDStates;
import com.example.demo2.define.Headers;
import com.example.demo2.define.Variables;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateContext;
import org.springframework.statemachine.action.Action;
import reactor.core.publisher.Mono;

import java.util.Map;

public class TrackAction implements Action<CDStates, CDEvents> {

    @Override
    public void execute(StateContext<CDStates, CDEvents> context) {
        Map<Object, Object> variables = context.getExtendedState().getVariables();
        Object trackshift = context.getMessageHeader(Headers.TRACKSHIFT.toString());
        Object track = variables.get(Variables.TRACK);
        Object cd = variables.get(Variables.CD);
        if (trackshift instanceof Integer && track instanceof Integer && cd instanceof Cd) {
            int next = ((Integer)track) + ((Integer)trackshift);
            if (next >= 0 &&  ((Cd)cd).getTracks().length > next) {
                variables.put(Variables.ELAPSEDTIME, 0l);
                variables.put(Variables.TRACK, next);
            } else if (((Cd)cd).getTracks().length <= next) {
                context.getStateMachine()
                        .sendEvent(Mono.just(MessageBuilder
                                .withPayload(CDEvents.STOP).build()))
                        .subscribe();
            }
        }
    }
}